﻿using NaireSystem.Api;
using NaireSystem.Api.Dto;
using NaireSystem.Datas;
using NaireSystem.Enums;
using NaireSystem.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TYBase;
using TYControls;

namespace NaireSystem.Views
{
    /// <summary>
    /// CtrlNaireCreate.xaml 的交互逻辑
    /// </summary>
    public partial class CtrlNaireCreate : TYUserControl
    {
        ViewModelNaireCreate vm = new ViewModelNaireCreate();
        public CtrlNaireCreate()
        {
            InitializeComponent();
            this.DataContext = vm;
            this.Loaded += CtrlNaireCreate_Loaded;
        }

        private async void CtrlNaireCreate_Loaded(object sender, RoutedEventArgs e)
        {
            //搜索未完成的
            if (await InitOffice() == false)
            {
                return;
            }
            pager_record_CurrentPageChanged(null, null);
        }

        #region 题库的
        private async Task<bool> LoadUser()
        {
            vm.NaireQts.ListUser.Clear();
            var rData = await Run(() =>
            {
                return ServerApi.GetUserList();
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return false;
            }
            rData.data.ForEach(x =>
            {
                vm.NaireQts.ListUser.Add(new StringStringData { Key = x.s_ic_no, Value = x.s_name });
            });
            return true;
        }

        private async void BtnClick_Search(object sender, RoutedEventArgs e)
        {
            int pageIndex = pager.CurrentPage;
            QtQueryDto queryDto = new QtQueryDto()
            {
                createCode = vm.NaireQts.SelectedUser?.Key,
                tag = vm.NaireQts.SelectTag?.Value,
                title = vm.NaireQts.Title,
                examType = (int)EnumExamType.Naire,
            };
            vm.NaireQts.ListQt.Clear();

            var rData = await Run(() =>
            {
                return QtApi.GetListQt(new PageInfo(pageIndex, 10), queryDto);

            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return;
            }
            pager.MaxPage = rData.page.PageCount();
            rData.data.ForEach(x =>
            {
                QtModel quetionModel = UIDataHelper.DataAsUI(x);
                quetionModel.Index = (pageIndex - 1) * rData.page.PageSize + vm.NaireQts.ListQt.Count + 1;
                vm.NaireQts.ListQt.Add(quetionModel);
            });

        }

        private void BtnClick_EditItem(object sender, RoutedEventArgs e)
        {
            var dx = (sender as Button).DataContext as QtModel;
            ViewNaireEditQt view = new ViewNaireEditQt(dx.data);
            view.ShowDialog();
            BtnClick_Search(null, null);
        }

        private async Task<bool> InitDictData()
        {
            var ret = await Run(() =>
            {
                return DictTypeApi.GetList(new DBEntity.Tbl_DictType { dict_type = "naire_tag_type" });
            });
            if (ret.code != 0)
            {
                this.ShowMsg(ret.msg);
                return false;
            }
            vm.NaireQts.ListTag.Clear();
            foreach (var item in ret.data)
            {
                IntStringData model = new IntStringData
                {
                    Key = item.dict_type_id,
                    Value = item.dict_type_name
                };
                vm.NaireQts.ListTag.Add(model);
            }
            return true;
        }

        private async void BtnClick_DeleteItem(object sender, RoutedEventArgs e)
        {
            var model = (sender as Button).DataContext as QtModel;
            if (!this.ShowYesNo($"是否确认删除 ：{model.Title}"))
            {
                return;
            }
            var ret = await Run(() =>
            {
                return QtApi.DeleteQt(model.data.qtId);
            });

            if (ret.code != 0)
            {
                this.ShowMsg(ret.msg);
                return;
            }

            BtnClick_Search(null, null);
        }

        private void pager_CurrentPageChanged(object sender, Panuon.WPF.SelectedValueChangedRoutedEventArgs<int> e)
        {
            BtnClick_Search(null, null);
        }


        #endregion

        private async void pager_record_CurrentPageChanged(object sender, Panuon.WPF.SelectedValueChangedRoutedEventArgs<int> e)
        {
            int pageIndex = pager_record.CurrentPage;
            TestQueryDto queryDto = new TestQueryDto()
            {
                //dtEnd = vm.DtEnd,
                //dtStart = vm.DtStart,
                //title = vm.Title,
                status = (int)EnumExamStatus.NotPublish,
                examType = (int)EnumExamType.Naire,
            };
            vm.ListNaireRecord.Clear();
            var rData = await Run(() =>
            {
                return ExamApi.GetListMyCreateNaireTest(new PageInfo(pageIndex, 5), queryDto);
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return;
            }
            pager_record.MaxPage = rData.page.PageCount();
            rData.data.ForEach(x =>
            {
                NaireRecordModel quetionModel = UIDataHelper.DataAsUI(x);
                quetionModel.Index = (pageIndex - 1) * rData.page.PageSize + vm.ListNaireRecord.Count + 1;
                vm.ListNaireRecord.Add(quetionModel);
            });
        }

        async Task<bool> InitOffice()
        {
            var rData = await Run(() =>
            {
                return OfficeApi.GetListDeptInfo();
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return false;
            }
            vm.ListOffice.Clear();

            rData.data?.ForEach(x =>
            {
                vm.ListOffice.Add(new DeptModel
                {
                    Name = x.s_office,
                    Id = x.s_mark,
                    UserCount = x.userCount,
                });
            });
            return true;
        }
        private async void BtnClick_SelectTest(object sender, RoutedEventArgs e)
        {
            var dx = (sender as Button).DataContext as NaireRecordModel;
            if (!this.ShowYesNo($"是否进入问卷编辑:{dx.Title}"))
                return;
            //开始查询
            var rData = await Run(() =>
            {
                return ExamApi.GetExamWithDepts(dx.data.examUuid);
            });
            vm.EditTest.examUuid = null;
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return;
            }
            vm.EditTest.examUuid = rData.data.exam.examUuid;
            vm.EditTest.Title = dx.data.title;
            vm.EditTest.ListQt.Clear();
            foreach (var item in vm.ListOffice)
            {
                if (rData.data.listDept != null)
                {
                    if (rData.data.listDept.Count(x => x.deptUuid == item.Id) > 0)
                    {
                        item.IsSelected = true;
                        continue;
                    }
                }
                item.IsSelected = false;
            }


            if (rData.data.listQt != null)
            {
                rData.data.listQt.ForEach(x =>
                {
                    QtModel quetionModel = UIDataHelper.DataAsUI(x);
                    quetionModel.Index = vm.EditTest.ListQt.Count + 1;
                    vm.EditTest.ListQt.Add(quetionModel);
                });
            }
        }

        private void BtnClick_AddToTest(object sender, RoutedEventArgs e)
        {
            var dx = (sender as Button).DataContext as QtModel;
            QtModel qt = UIDataHelper.DataAsUI(dx.data);
            qt.Index = vm.EditTest.ListQt.Count + 1;
            vm.EditTest.ListQt.Add(qt);
        }

        private void BtnClick_DeleteFromTest(object sender, RoutedEventArgs e)
        {
            var dx = (sender as Button).DataContext as QtModel;
            //QtModel qt = UIDataHelper.DataAsUI(dx.data);
            vm.EditTest.ListQt.Remove(dx);
            for (int i = 0; i < vm.EditTest.ListQt.Count; i++)
            {
                vm.EditTest.ListQt[i].Index = i + 1;
            }
        }

        bool AsExamData(out CreateTestDto exam)
        {
            exam = new CreateTestDto();
            if (vm.EditTest.Title.Null())
            {
                this.ShowMsg("请输入标题");
                return false;
            }
            Dictionary<string, List<string>> listDeptUser = null;
            List<Tbl_ExamDept> listTestDept = new List<Tbl_ExamDept>();

            foreach (var item in vm.ListOffice)
            {
                if (item.IsSelected)
                    listTestDept.Add(new Tbl_ExamDept { deptUuid = item.Id });
            }

            List<IdAndScoreVo> listId = new List<IdAndScoreVo>();
            foreach (var item in vm.EditTest.ListQt)
            {
                listId.Add(new IdAndScoreVo { id = item.data.qtId, score = item.Score });
            }

            exam = new CreateTestDto()
            {
                exam = new Tbl_Exam
                {
                    createCode = AppData.user.s_ic_no,
                    createTime = DateTime.Now,
                    status = 0,
                    examType = (int)EnumExamType.Naire,
                    title = vm.EditTest.Title,
                    examUuid = vm.EditTest.examUuid,
                },
                listIdAndScore = listId,
                listDeptUser = listDeptUser,
                listDept = listTestDept,
            };
            return true;
        }

        private async void BtnClick_SaveExam(object sender, RoutedEventArgs e)
        {
            if (!AsExamData(out var examData))
            {
                return;
            }
            examData.exam.status = (int)EnumExamStatus.NotPublish;
            var rData = await Run(() =>
            {
                return ExamApi.CreateTest(examData);
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                pager_record_CurrentPageChanged(null, null);
                return;
            }
            vm.EditTest.examUuid = rData.data.examUuid;
            this.ShowMsg("发布成功!");
            pager_record_CurrentPageChanged(null, null);
        }

        private async void BtnClick_PublishExam(object sender, RoutedEventArgs e)
        {
            if (!AsExamData(out var examData))
            {
                return;
            }
            examData.exam.status = (int)EnumExamStatus.Publish;
            var rData = await Run(() =>
            {
                return ExamApi.CreateTest(examData);
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                pager_record_CurrentPageChanged(null, null);
                return;
            }
            vm.EditTest.examUuid = rData.data.examUuid;
            this.ShowMsg("发布成功!");
            pager_record_CurrentPageChanged(null, null);
        }

        private void BtnClick_CreateExam(object sender, RoutedEventArgs e)
        {
            vm.EditTest.ListQt.Clear();
            vm.EditTest.examUuid = "";
            vm.EditTest.Title = "";
            foreach (var item in vm.ListOffice)
            {
                item.IsSelected = false;
            }
        }
    }
}
